<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/8/16
 * Time: 15:34
 */

namespace app\modules\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\UnauthorizedHttpException;

class CommonController extends Controller
{
        public $layout = 'layout1';
        protected $mustLogin = [];
        protected $actions = ['*'];
        protected $except = [];

//        行为

    /**
     * @return array
     */
        public function behaviors()
        {
            return [
                'access' => [
//                    过滤器
                    'class' => AccessControl::className(),
                    'user' => 'admin',
                    'only' => $this->actions,
                    'except' => $this->except,
                    'rules' => [
                        [
                            'allow' => false,
                            'actions' => empty($this->mustLogin) ? [] : $this->mustLogin,
                            'roles' => ['?'],
                        ],
                        [
                            'allow' => true,
                            'actions' => empty($this->mustLogin) ? [] : $this->mustLogin,
                            'roles' => ['@']
                        ]
                    ]
                ]
            ];
        }

    /**
     * 每个操作前执行的
     * @param $action
     * @return bool|void
     */
        public function beforeAction($action)
        {
            if (!parent::beforeAction($action)) {
                return false;
            }
            $controller = $action->controller->id;
            $actionName = $action->id;
            //根据Rbac来写,判断这个用户是否拥有这个对应的权限
            if (Yii::$app->admin->can($controller.'/*')) {
                return true;
            }
            if (Yii::$app->admin->can($controller."/".$actionName)) {
                return true;
            }
            throw new UnauthorizedHttpException("对不起，你没有访问".$controller.'/'.$actionName."的权限");

        }
}